package cn.lngaosu.lwyd.module.integration.service.weibostatusesusertimeline;

import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.lngaosu.lwyd.framework.common.util.http.HttpUtils;
import cn.lngaosu.lwyd.module.infra.service.config.ConfigService;
import cn.lngaosu.lwyd.module.integration.dal.dataobject.weibouserscounts.WeiboUserscountsDO;
import cn.lngaosu.lwyd.module.integration.service.apptoken.AppTokenService;
import cn.lngaosu.lwyd.module.integration.service.weixinvideoliverecord.WeixinvideoLiverecordServiceImpl;
import cn.lngaosu.lwyd.module.system.dal.dataobject.webinterfacelog.WebinterfaceLogDO;
import cn.lngaosu.lwyd.module.system.dal.mysql.webinterfacelog.WebinterfaceLogMapper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.*;
import cn.lngaosu.lwyd.module.integration.controller.admin.weibostatusesusertimeline.vo.*;
import cn.lngaosu.lwyd.module.integration.dal.dataobject.weibostatusesusertimeline.WeiboStatusesUsertimelineDO;
import cn.lngaosu.lwyd.framework.common.pojo.PageResult;
import cn.lngaosu.lwyd.framework.common.pojo.PageParam;
import cn.lngaosu.lwyd.framework.common.util.object.BeanUtils;

import cn.lngaosu.lwyd.module.integration.dal.mysql.weibostatusesusertimeline.WeiboStatusesUsertimelineMapper;

import static cn.lngaosu.lwyd.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.lngaosu.lwyd.framework.common.util.collection.CollectionUtils.convertList;
import static cn.lngaosu.lwyd.framework.common.util.collection.CollectionUtils.diffList;
import static cn.lngaosu.lwyd.module.integration.enums.ErrorCodeConstants.*;

/**
 * 最新发表的微博列表 Service 实现类
 *
 * @author 张恒
 */
@Service
@Validated
public class WeiboStatusesUsertimelineServiceImpl implements WeiboStatusesUsertimelineService {
    private static final Logger logger = LoggerFactory.getLogger(WeiboStatusesUsertimelineServiceImpl.class);

    @Resource
    private WeiboStatusesUsertimelineMapper weiboStatusesUsertimelineMapper;
    @Resource
    private AppTokenService appTokenService;
    @Resource
    private ConfigService configService;
    @Resource
    private WebinterfaceLogMapper webinterfaceLogMapper;

    @Override
    public Long createWeiboStatusesUsertimeline(WeiboStatusesUsertimelineSaveReqVO createReqVO) {
        // 插入
        WeiboStatusesUsertimelineDO weiboStatusesUsertimeline = BeanUtils.toBean(createReqVO, WeiboStatusesUsertimelineDO.class);
        weiboStatusesUsertimelineMapper.insert(weiboStatusesUsertimeline);
        // 返回
        return weiboStatusesUsertimeline.getId();
    }

    @Override
    public void updateWeiboStatusesUsertimeline(WeiboStatusesUsertimelineSaveReqVO updateReqVO) {
        // 校验存在
        validateWeiboStatusesUsertimelineExists(updateReqVO.getId());
        // 更新
        WeiboStatusesUsertimelineDO updateObj = BeanUtils.toBean(updateReqVO, WeiboStatusesUsertimelineDO.class);
        weiboStatusesUsertimelineMapper.updateById(updateObj);
    }

    @Override
    public void deleteWeiboStatusesUsertimeline(Long id) {
        // 校验存在
        validateWeiboStatusesUsertimelineExists(id);
        // 删除
        weiboStatusesUsertimelineMapper.deleteById(id);
    }

    @Override
        public void deleteWeiboStatusesUsertimelineListByIds(List<Long> ids) {
        // 校验存在
        validateWeiboStatusesUsertimelineExists(ids);
        // 删除
        weiboStatusesUsertimelineMapper.deleteByIds(ids);
        }

    private void validateWeiboStatusesUsertimelineExists(List<Long> ids) {
        List<WeiboStatusesUsertimelineDO> list = weiboStatusesUsertimelineMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(WEIBO_STATUSES_USERTIMELINE_NOT_EXISTS);
        }
    }

    private void validateWeiboStatusesUsertimelineExists(Long id) {
        if (weiboStatusesUsertimelineMapper.selectById(id) == null) {
            throw exception(WEIBO_STATUSES_USERTIMELINE_NOT_EXISTS);
        }
    }

    @Override
    public WeiboStatusesUsertimelineDO getWeiboStatusesUsertimeline(Long id) {
        return weiboStatusesUsertimelineMapper.selectById(id);
    }

    @Override
    public PageResult<WeiboStatusesUsertimelineDO> getWeiboStatusesUsertimelinePage(WeiboStatusesUsertimelinePageReqVO pageReqVO) {
        return weiboStatusesUsertimelineMapper.selectPage(pageReqVO);
    }

    @Override
    public void syncWeiboStatusesUsertimeline() {
        // 获取token
        String weiboToken = appTokenService.getWeiboToken();
        if (StringUtils.isEmpty(weiboToken)) {
            throw exception(WEIBO_TOKEN_NOT_EXISTS);
        }

        // 接口配置
        String configValue = configService.getConfigValueByKey("weiboConfig");
        if (StringUtils.isEmpty(configValue)) {
            throw exception(INTERFACE_CONFIG_NOT_EXISTS);
        }

        JSONObject configJo = JSONObject.parseObject(configValue);
        // 接口开关
        String onOff = configJo.getString("onOff");
        if (!"on".equals(onOff)) {
            throw exception(INTERFACE_CONFIG_NOT_EXISTS);
        }

        // 获取地址
        String statusesUserTimelineUrl = configJo.getString("statusesUserTimelineUrl");
        statusesUserTimelineUrl = statusesUserTimelineUrl + "?access_token=" + weiboToken;

        // 构造请求参数
        JSONObject params = new JSONObject();

        // 初始化日志数据（默认成功）
        WebinterfaceLogDO webinterfaceLogDO = new WebinterfaceLogDO();
        webinterfaceLogDO.setInterfaceSystemName("微博");
        webinterfaceLogDO.setInterfaceName("获取最新发表的微博列表");
        webinterfaceLogDO.setInterfaceUrl(statusesUserTimelineUrl);
        webinterfaceLogDO.setInterfaceRequestMethod("GET");
        webinterfaceLogDO.setInterfaceParam(null);
        webinterfaceLogDO.setInterfaceStatus("成功");
        webinterfaceLogMapper.insert(webinterfaceLogDO);

        try {
            String result = HttpUtils.get(statusesUserTimelineUrl, new HashMap<>());
            // 解析接口结果
            JSONObject resultJo = JSONObject.parseObject(result);
            Integer errcode = resultJo.getInteger("error_code");
            if (ObjectUtils.isNotEmpty(errcode)) {
                webinterfaceLogDO.setInterfaceStatus("失败");
                webinterfaceLogDO.setInterfaceErrorInfo(result);
                webinterfaceLogMapper.updateById(webinterfaceLogDO);
                return;
            }

            // 处理接口数据
            JSONArray allJa = new JSONArray();
            JSONArray resultJa = resultJo.getJSONArray("statuses");
            allJa.addAll(resultJa);
            Long max_id = resultJo.getLong("max_id");
            while (max_id != 0L) {
                result = HttpUtils.get(statusesUserTimelineUrl + "&max_id=" + max_id, new HashMap<>());
                // 解析接口结果
                resultJo = JSONObject.parseObject(result);
                errcode = resultJo.getInteger("error_code");
                if (ObjectUtils.isNotEmpty(errcode)) {
                    webinterfaceLogDO.setInterfaceStatus("失败");
                    webinterfaceLogDO.setInterfaceErrorInfo(result);
                    webinterfaceLogMapper.updateById(webinterfaceLogDO);
                    break;
                }
                resultJa = resultJo.getJSONArray("statuses");
                allJa.addAll(resultJa);
                max_id = resultJo.getLong("max_id");
            }
            webinterfaceLogDO.setInterfaceErrorInfo(result);
            webinterfaceLogMapper.updateById(webinterfaceLogDO);

            for (int i = 0; i < allJa.size(); i++) {
                JSONObject jsonObject = allJa.getJSONObject(i);
                Long weiboId = jsonObject.getLong("id");
                LocalDate localDate = LocalDate.now();
                JSONObject userJo = jsonObject.getJSONObject("user");
                Long weiboUid = userJo.getLong("id");
                WeiboStatusesUsertimelineDO weiboStatusesUsertimelineDO = BeanUtils.toBeanIgnoreProperties(jsonObject, WeiboStatusesUsertimelineDO.class, CopyOptions.create().setIgnoreProperties("id"));
                weiboStatusesUsertimelineDO.setWeiboId(weiboId);
                weiboStatusesUsertimelineDO.setSyncDate(localDate);
                weiboStatusesUsertimelineDO.setDetailMessage(result);
                weiboStatusesUsertimelineDO.setWeiboUid(weiboUid);

                // 判断数据是更新还是插入
                LambdaQueryWrapper<WeiboStatusesUsertimelineDO> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(WeiboStatusesUsertimelineDO::getWeiboId, weiboId);
                List<WeiboStatusesUsertimelineDO> weiboStatusesUsertimelineDOS = weiboStatusesUsertimelineMapper.selectList(queryWrapper);
                if (CollectionUtils.isNotEmpty(weiboStatusesUsertimelineDOS)) {
                    weiboStatusesUsertimelineDO.setId(weiboStatusesUsertimelineDOS.get(0).getId());
                }

                weiboStatusesUsertimelineMapper.insertOrUpdate(weiboStatusesUsertimelineDO);
            }

        } catch (Exception e) {
            webinterfaceLogDO.setInterfaceStatus("失败");
            webinterfaceLogDO.setInterfaceErrorInfo(e.getMessage());
            webinterfaceLogMapper.updateById(webinterfaceLogDO);
            logger.error("微博【获取最新发表的微博列表】接口调用失败！", e);
        }
    }

}